<?php
//确保在连接客户端时不会超时
	set_time_limit(0);
	//设置IP和端口号
	$address = "0.0.0.0";
	$port = 8888; //调试的时候，可以多换端口来测试程序！
	$buff = 0;
	/**
	 * 创建一个SOCKET 
	 * AF_INET=是ipv4 如果用ipv6，则参数为 AF_INET6
	 * SOCK_STREAM为socket的tcp类型，如果是UDP则使用SOCK_DGRAM
	 */
	$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() 失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
	//阻塞模式
	socket_set_block($sock) or die("socket_set_block() 失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
	//绑定到socket端口
	$result = socket_bind($sock, $address, $port) or die("socket_bind() 失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
	//开始监听
	$result = socket_listen($sock, 4) or die("socket_listen() 失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
	echo "OK\nBinding the socket on $address:$port ... ";
	echo "OK\nNow ready to accept connections.\nListening on the socket ... \n";
	// never stop the daemon
	//它接收连接请求并调用一个子连接Socket来处理客户端和服务器间的信息
	while(true)
	{
	$msgsock = socket_accept($sock) or  die("socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "/n");
	$fp = fopen('../images/my.bmp','w+');
	do{    
		//读取客户端数据
		echo "Read client data \n";

		//socket_read函数会一直读取客户端数据,直到遇见\n,\t或者\0字符.PHP脚本把这写字符看做是输入的结束符.
		$buff = socket_read($msgsock,1024);
		//socket_recv($msgsock,$buff,99999,0);

		if(!$buff)
		{
			echo "read already\n";
			break;
		}


		$size = fwrite($fp, $buff); 
	//	echo $size;
		$buff = 0;
	} while (true);
	//socket_close($sock);
	}
?>
